package edu.neu.javaweb.filter;

import io.github.biezhi.anima.Anima;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class EncodeAndSetSessionFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String jdbcUrl = "jdbc:mysql://146.56.213.198:3306/hr?characterEncoding=utf-8&serverTimezone=GMT%2B8";
        String user = "test";
        String pass = "test";
        Anima.open(jdbcUrl, user, pass);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 设置session
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpSession session = httpServletRequest.getSession();
        session.setMaxInactiveInterval(30);
        Object isLoginSession = session.getAttribute("isLogin");
        if (isLoginSession == null) {
            // 如果还没有isLogin属性，说明是第一次会话，设一个false
            httpServletRequest.getSession().setAttribute("isLogin", false);
        }

        // 编码统一
        servletRequest.setCharacterEncoding("utf-8");
//        servletResponse.setCharacterEncoding("utf-8");
//        servletResponse.setContentType("text/html;charset=utf-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
